package com.allwees.bs.c.module.payment.service.impl;

import com.allwees.bs.c.module.order.entity.OrderEntity;
import com.allwees.bs.c.module.order.repository.OrderRepository;
import com.allwees.bs.c.module.order.service.IOrderService;
import com.allwees.bs.c.module.payment.entity.PaymentLogEntity;
import com.allwees.bs.c.module.payment.req.OceanpayCallback;
import com.allwees.bs.c.module.payment.service.IPaymentLogService;
import com.allwees.bs.c.module.payment.service.OceanpayService;
import com.allwees.bs.core.model.order.wf.order.EOrderState;
import com.allwees.bs.core.model.payment.enums.EPaymentType;
import com.allwees.bs.core.modelbase.constant.ResultEnum;
import com.allwees.bs.core.modelbase.exception.BusinessException;
import com.allwees.support.payment.EPayMethod;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Daniel
 * @version 1.0.0
 * @since 2020/12/6 14:00
 */
@Service
@Slf4j
public class OceanpayServiceImpl implements OceanpayService {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IPaymentLogService paymentLogService;

    @Autowired
    private OrderRepository orderRepository;

    @Override
    public OrderEntity getOrder(String orderUuid) {
        OrderEntity order = this.orderRepository.getByUuid(orderUuid);
        if (order == null) {
            throw BusinessException.getInstance(ResultEnum.NOT_FOUND);
        }
        if (!EOrderState.CREATED.equals(order.getState()) || order.isAmtPayedOfCoupon()) {
            throw BusinessException.getInstance(ResultEnum.PAYMENT_ORDER_STATE_IS_NOT_UNPAID);
        }
        paymentLogService.create(null, IPaymentLogService.PAYMENT_STATE_CREATED, EPayMethod.CREDIT_CARD, order);
        return order;
    }

    @Override
    public boolean paySuccess(OceanpayCallback callback) {
        PaymentLogEntity paymentLog = paymentLogService.payed(callback.getOrder_number(), callback.getCard_number(), callback.getPayment_id());
        if (paymentLog == null) {
            return false;
        }
        // 支付成功，通知订单修改状态
        orderService.payOrder(paymentLog.getOrderUuid(), paymentLog.getUuid(), EPaymentType.OCEANPAY);
        return true;
    }
}
